package cn.tjie.basic.controller;

import cn.tjie.basic.util.AjaxResult;
import cn.tjie.basic.util.FastDfsUtils;
import jdk.nashorn.api.scripting.AbstractJSObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传和删除接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    //@RequestPart对复杂表单项的处理，默认name="file",与上传文件的name属性值一致
    public AjaxResult loadFile(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();//XXX.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//jpg
            String filePath = FastDfsUtils.upload(file.getBytes(), extName);//调用工具类
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.setObj(filePath);//把上传后的路径返回回去
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 删除
     * @param path
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String path){
        try {
            //path = /goup1/xxxxx/yyyy
            String s = path.substring(1);//goup1/xxxxx/yyyy
            String groupName = s.substring(0, s.indexOf("/"));//group1
            String fileName = s.substring(s.indexOf("/") + 1);// xxxxx/yyyy
            //调用工具类
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
}
